/*
 * File used for communication over UART intefrface to a connected PC
 */
#include "uart.h"
#include "avr/io.h"

// The transfer baudrate for communication
#define BAUDRATE 38400
// Multiplier used to calculate the right output representation
#define MULTIPLY 8UL
// Baudrate as machine specific value
#define BAUD ((F_CRYSTAL/(MULTIPLY*BAUDRATE))-1)

/**
 * Initialises the USART0 port for communication
 */
void init_USART0() {
	PRR0=(0<<PRUSART0);
	UCSR0B=0x00;
	//Set asynchronous normal mode
	UCSR0A=(1<<U2X0);
	//Set baud rate
	UBRR0H=(unsigned char)(BAUD>>8);
	UBRR0L=(unsigned char)BAUD;
	//Set frame format: 8data, 1 stop bit
	UCSR0C=(1<<USBS0)|(3<<UCSZ00);
	//Enable receiver and transmitter
	UCSR0B=(1<<RXEN0)|(1<<TXEN0);
}

/**
 * Initialises the USART1 port for communication
 */
void init_USART1() {
	PRR1=(0<<PRUSART1);
	UCSR1B=0x00;
	//Set asynchronous normal mode
	UCSR1A=(1<<U2X1);
	//Set baud rate
	UBRR1H=(unsigned char)(BAUD>>8);
	UBRR1L=(unsigned char)BAUD;
	//Set frame format: 8data, 1 stop bit
	UCSR1C=(1<<USBS1)|(3<<UCSZ10);
	//Enable receiver and transmitter
	UCSR1B=(1<<RXEN1)|(1<<TXEN1);
}

/**
 * Initialises the USART2 port for communication
 */
void init_USART2() {
	PRR1=(0<<PRUSART2);
	UCSR2B=0x00;
	//Set asynchronous normal mode
	UCSR2A=(1<<U2X2);
	//Set baud rate
	UBRR2H=(unsigned char)(BAUD>>8);
	UBRR2L=(unsigned char)BAUD;
	//Set frame format: 8data, 1 stop bit
	UCSR2C=(1<<USBS2)|(3<<UCSZ20);
	//Enable receiver and transmitter
	UCSR2B=(1<<RXEN2)|(1<<TXEN2);
}

/**
 * Initialises the USART3 port for communication
 */
void init_USART3() {
	PRR1=(0<<PRUSART3);
	UCSR3B=0;
	//Set asynchronous normal mode
	UCSR3A=(1<<U2X3);
	//Set baud rate
	UBRR3|=BAUD;
//	UBRR3H|=(unsigned char)(BAUD>>8);
//	UBRR3L|=(unsigned char)BAUD;
	//Set frame format: 8data, 1 stop bit
	UCSR3C|=(0<<UMSEL30)|(0<<UMSEL31);
	UCSR3C|=(0<<USBS3);
	UCSR3C|=(3<<UCSZ30);
	UCSR3C|=(0<<UCPOL3);
	//Enable receiver and transmitter
	UCSR3B|=(1<<RXEN3)|(1<<TXEN3);
}


void init_uart() {
//	init_USART0();
//	init_USART1();
//	init_USART2();

	init_USART3();
	put_uart("[INIT] Uart"); put_uart(CRLF);
}
